﻿using System;
using System.ComponentModel;
using INTEX.DataBase;
using INTEX.DataBase.Tools;
using ReflectionStudio.Core.Events;
using System;
using System.Data;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Input;
namespace WPFExcelReport
{
    /// <summary>
    /// Interaction logic for EditEventWindow.xaml
    /// </summary>
    public partial class VWPLANVKP : ViewBase
    {
        ApplicationBase app
        {
            get
            {
                return ApplicationBase.Instance;
            }
        }
        public INTEXDBC INTEXDBC
        {
            get
            {
                return app.INTEXDBC;
            }
        }
        public INTEXBL INTEXBL
        {
            get
            {
                return app.INTEXBL;
            }
        }

        public DataRow dwVKPOS
        {
            get
            {
                return vm.dwVKP;
            }
        }


        BindingListCollectionView cvJABP
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgJABP.ItemsSource);
            }
        }
        BindingListCollectionView cvWABP
        {
            get
            {
                return (BindingListCollectionView)CollectionViewSource.GetDefaultView(dlgWABP.ItemsSource);
            }
        }
        CollectionViewSource vwABAX
        {
            get
            {
                return (CollectionViewSource)this.TryFindResource("vwABAX");
            }
        }
        DataRow dwABAX
        {
            get
            {
                if (vwABAX.View == null)
                    return null;
                if ((DataRowView)vwABAX.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwABAX.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwWARP
        {
            get
            {
                return (CollectionViewSource)TryFindResource("vwWARP");
            }
        }
        DataRow dwWARP
        {
            get
            {
                if (vwWARP.View == null)
                    return null;
                if ((DataRowView)vwWARP.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwWARP.View.CurrentItem).Row;
            }
        }
        CollectionViewSource vwWEFT
        {
            get
            {
                return (CollectionViewSource)TryFindResource("vwWEFT");
            }
        }
        DataRow dwWEFT
        {
            get
            {
                if (vwWEFT.View == null)
                    return null;
                if ((DataRowView)vwWEFT.View.CurrentItem == null)
                    return null;
                return ((DataRowView)vwWEFT.View.CurrentItem).Row;
            }
        }
        ITXABPLANData ITXABPLANData;
        bool IsLoaded = false;
        MainViewModel vm;
        SETINTEXDB SetMaster
        {
            get
            {
                return vm.SetMaster;
            }
        }
        SETINTEXDB SetEnv
        {
            get
            {
                return vm.SetEnv;
            }
        }
        SETINTEXDB SetDetail
        {
            get
            {
                return vm.SetDetail;
            }
        }
        public bool CanPublish
        {
            get { return vm.CanPublish; }
            set
            {
                vm.CanPublish = value;
            }
        }
        public bool CanDelete
        {
            get { return vm.CanDelete; }
            set
            {
                vm.CanDelete = value;
            }
        }
        DataRow dwYARNABP = null;
        ITXEXRPT ITXEXRPT;
        public VWPLANVKP()
        {
            InitializeComponent();
            this.Loaded += Windows_Loaded;
            ITXEXRPT = new ITXEXRPT();
            ITXEXRPT.Root = "C:\\IntexReport";
            ITXEXRPT.strCompany = app.company;
            ITXEXRPT.PrintType = "OpenExcel";
        }
        string filter = "";
        DataRow dwRawYarn = null;
        void Windows_Loaded(object sender, System.Windows.RoutedEventArgs e)
        {
            if (DesignerProperties.GetIsInDesignMode(this))
                return;
            if (IsLoaded)
                return;
            IsLoaded = true;
            if (vm == null)
            {
                vm = this.DataContext as MainViewModel;
            }
            vwWARP.View.CurrentChanged += vwWARP_CurrentChanged;
            vwWEFT.View.CurrentChanged += vwWEFT_CurrentChanged;
            filter = "ABAWAKZ='G' AND ABPWAKZ='W'";//这里标明是经纱，W是经轴的意思
            cvJABP.CustomFilter = filter;
            filter = "ABAWAKZ='G' AND ABPWAKZ='R'";//这里标明是纬纱R是坯布的意思
            cvWABP.CustomFilter = filter;
        }

        void vwWARP_CurrentChanged(object sender, System.EventArgs e)
        {
            if (dwWARP == null)
                return;
            dwRawYarn = dwWARP;
            if (dwRawYarn["ABASSTKWG"].ToString().Trim() == "0" || dwRawYarn["ABASSTKWG"].ToString().Trim() == "")
            {
                dwRawYarn["ABASSTKWG"] = dwRawYarn["ABARESMG"];
            }
            string _krs = dwRawYarn["ABAAUFKRS"].ToString();
            string _lfd = dwRawYarn["ABAAUFLFD"].ToString();
            string _pos = dwRawYarn["ABAAUFPOS"].ToString();
            dwWARP["SELLERNAME"] = dwWARP["SELLERNAME"].ToString().Trim();
            var query = from DataRow row in SetDetail.Tables["ABPOS"].AsEnumerable()
                        where row["ABPAUFKRS"].ToString() == _krs
                        && row["ABPAUFLFD"].ToString() == _lfd
                        && row["ABPAUFPOS"].ToString() == _pos
                        select row;
            foreach (DataRow row in query)
            {
                dwYARNABP = row;
            }
            vm.BASEQTY = Convert.ToDouble(dwRawYarn["ABASSTKWG"].ToString()) / 1000;
            vm.MQTY = vm.BASEQTY;
            query = from DataRow row in SetDetail.Tables["ICC_ABAX"].AsEnumerable()
                    where row["ABAVKAUFKRS"].ToString() == _krs
                    && row["ABAVKAUFLFD"].ToString() == _lfd
                    && row["ABAVKAUFPOS"].ToString() == _pos
                    select row;
            foreach (DataRow row in query)
            {
                vm.GR02 = Convert.ToDouble(row["R02"].ToString());
                vm.NGR02 = vm.GR02;
                dwRawYarn["FBRTU"] = vm.GR02;
                vm.GF01 = Convert.ToDouble(row["F01"].ToString());                
                vm.GF02 = Convert.ToDouble(row["F02"].ToString());
                vm.NGF02 = vm.GF02; 
            }
        }

        void vwWEFT_CurrentChanged(object sender, System.EventArgs e)
        {
            try
            { 
                if (dwWEFT == null)
                    return;
                
                dwRawYarn = dwWEFT;
                if (dwRawYarn["ABASSTKWG"].ToString().Trim() == "0" || dwRawYarn["ABASSTKWG"].ToString().Trim() == "")
                {
                    dwRawYarn["ABASSTKWG"] = dwRawYarn["ABARESMG"];
                }
                dwWEFT["SELLERNAME"] = dwWEFT["SELLERNAME"].ToString().Trim();
                string _krs = dwRawYarn["ABAAUFKRS"].ToString();
                string _lfd = dwRawYarn["ABAAUFLFD"].ToString();
                string _pos = dwRawYarn["ABAAUFPOS"].ToString();

                var query = from DataRow row in SetDetail.Tables["ABPOS"].AsEnumerable()
                            where row["ABPAUFKRS"].ToString() == _krs
                            && row["ABPAUFLFD"].ToString() == _lfd
                            && row["ABPAUFPOS"].ToString() == _pos
                            select row;
                foreach (DataRow row in query)
                {
                    dwYARNABP = row;
                }

                vm.BASEQTY = Convert.ToDouble(dwRawYarn["ABASSTKWG"].ToString()) / 1000;
                vm.MQTY = vm.BASEQTY;
                query = from DataRow row in SetDetail.Tables["ICC_ABAX"].AsEnumerable()
                        where row["ABAVKAUFKRS"].ToString() == _krs//ABAVKAUFKRS VK标明是查找该纱线的原纱：
                        && row["ABAVKAUFLFD"].ToString() == _lfd
                        && row["ABAVKAUFPOS"].ToString() == _pos
                        select row;
                foreach (DataRow row in query)
                {
                    vm.GR02 = Convert.ToDouble(row["R02"].ToString());
                    vm.NGR02 = vm.GR02;//这个地方就是获取了染缩，对吗？也就是显示在染缩文本框里面的值得来源
                    dwRawYarn["FBRTU"] = vm.GR02;//所谓染缩，指的是100kg色纱，需要150kg原纱。是否？你先改 你这样有问题，FBRTU不在ABPOS
                    vm.GF01 = Convert.ToDouble(row["F01"].ToString());
                    vm.GF02 = Convert.ToDouble(row["F02"].ToString());
                    vm.NGF02 = vm.GF02;
                  
                   //找个用不到的字段，临时表达
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnPublish_Click(object sender, RoutedEventArgs e)
        {
            DataSet SResult;
            SResult = new DataSet();
            SResult.Merge(SetDetail);
            DataRow[] rows = null;
            string filter = "";
            if (!vm.IsAB05)
            {
                filter = "ABPAUFART='VA'";
                rows = SResult.Tables["ABPOS"].Select(filter);
                foreach (DataRow row in rows)
                {
                    row.Delete();
                }
            }
            if (!vm.IsAB55)
            {
                filter = "ABPAUFART='PR' OR ABPAUFART='DI'";
                rows = SResult.Tables["ABPOS"].Select(filter);
                foreach (DataRow row in rows)
                {
                    row.Delete();
                }
            }
            if (!vm.IsAB45)
            {
                filter = "ABPAUFART='VW'";
                rows = SResult.Tables["ABPOS"].Select(filter);
                foreach (DataRow row in rows)
                {
                    row.Delete();
                }
            }
            SResult.AcceptChanges();
            vm.CanPublish = false;
            vm.CanDelete = true;
            vm.CanReplan = false;
            string path = @"C:\IntexReport\Data\JLTAV95";
            try
            {
                SResult.Tables["ABPOS"].TableName = "ABPOS_EXT";
                INTEXBL.Save2Xml(SResult, path);
                INTEXBL.AutoConvert(path, "JLTAV95");
                vm.ABPLFD = "X";
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void AdjustQty(DataRow dwABP)
        {
            try
            {
                if (dwABP == null)
                    return;
                double ABPSOLLMENGE1 = 0, ABPSOLLMENGE2 = 0, ABPSOLLMENGE3 = 0, ABPSOLLMENGE4 = 0, ABPSOLLMENGE5 = 0, ABPSOLLMENGE6 = 0, ABPSOLLMENGE7 = 0,
                    ABPSOLLMENGE8 = 0;
                ABPSOLLMENGE1 = Convert.ToDouble(dwABP["ABPSOLLMENGE1"].ToString());
                ABPSOLLMENGE2 = Convert.ToDouble(dwABP["ABPSOLLMENGE2"].ToString());
                ABPSOLLMENGE3 = Convert.ToDouble(dwABP["ABPSOLLMENGE3"].ToString());
                ABPSOLLMENGE4 = Convert.ToDouble(dwABP["ABPSOLLMENGE4"].ToString());
                ABPSOLLMENGE5 = Convert.ToDouble(dwABP["ABPSOLLMENGE5"].ToString());
                ABPSOLLMENGE6 = Convert.ToDouble(dwABP["ABPSOLLMENGE6"].ToString());
                ABPSOLLMENGE7 = Convert.ToDouble(dwABP["ABPSOLLMENGE7"].ToString());
                ABPSOLLMENGE8 = Convert.ToDouble(dwABP["ABPSOLLMENGE8"].ToString());
                double QtyBase = 1;
                double ratio = 1;
                switch (dwABP["ABPSME"].ToString())
                {
                    case "1":
                        QtyBase = ABPSOLLMENGE1;
                        break;
                    case "2":
                        QtyBase = ABPSOLLMENGE2;
                        break;
                    case "3":
                        QtyBase = ABPSOLLMENGE3;
                        break;
                    case "4":
                        QtyBase = ABPSOLLMENGE4;
                        break;
                    case "5":
                        QtyBase = ABPSOLLMENGE5;
                        break;
                    case "6":
                        QtyBase = ABPSOLLMENGE6;
                        break;
                    case "7":
                        QtyBase = ABPSOLLMENGE7;
                        break;
                    case "8":
                        QtyBase = ABPSOLLMENGE8;
                        break;
                }

                double mi = 0;
                #region====ABPOS=========
                for (int i = 1; i < 9; i++)
                {
                    mi = Convert.ToDouble(dwABP["ABPSOLLMENGE" + i.ToString()].ToString());
                    dwABP["ABPSOLLMENGE" + i.ToString()] = Math.Ceiling(mi * ratio / 100) * 100;
                }
                #endregion
                #region====Material==========
                var qMU = from DataRow row in SetDetail.Tables["ICC_ABAX"].AsEnumerable()
                          where row["ABAAUFKRS"].ToString() == dwABP["ABPAUFKRS"].ToString()
                          && row["ABAAUFLFD"].ToString() == dwABP["ABPAUFLFD"].ToString()
                          && row["ABAAUFPOS"].ToString() == dwABP["ABPAUFPOS"].ToString()
                          select row;
                foreach (DataRow dwMU in qMU)
                {
                    QtyBase = Convert.ToDouble(dwMU["ABARESMG"].ToString()) / 1000;
                    dwMU["ABARESMG"] = vm.MQTY * 1000;
                    dwMU["FBRTU"] = vm.NGR02;//这个是当前色纱
                 //   dwMU["R02"] = vm.NGR02;
                }
                ratio = vm.MQTY / QtyBase;
                qMU = from DataRow row in SetDetail.Tables["ICC_ABAX"].AsEnumerable()
                      where row["ABAVKAUFKRS"].ToString() == dwABP["ABPAUFKRS"].ToString()
                      && row["ABAVKAUFLFD"].ToString() == dwABP["ABPAUFLFD"].ToString()
                      && row["ABAVKAUFPOS"].ToString() == dwABP["ABPAUFPOS"].ToString()
                      select row;
                foreach (DataRow dwMU in qMU)
                {
                    double ABARESMG = Convert.ToDouble(dwMU["ABARESMG"].ToString());
                    dwMU["ABARESMG"] = Math.Ceiling(ABARESMG * ratio / 100) * 100;
                    dwMU["R02"] = vm.NGR02;//这里就保存率实际染缩  
                    dwMU["F01"] = vm.GF01;
                    dwMU["F02"] = vm.NGF02; 
                }
                SetEnv.Tables["ICC_ABAX"].Clear();
                SetEnv.Tables["ICC_ABAX"].Merge(SetDetail.Tables["ICC_ABAX"]);
                SetEnv.AcceptChanges();
                vm.MQTY = 0;
                #endregion
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void Mqty_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                AdjustQty(dwYARNABP);
                vwWEFT.View.MoveCurrentTo(-1);
                vwWARP.View.MoveCurrentTo(-1);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnDeleteABON_Click(object sender, RoutedEventArgs e)
        {
            string krs = dwVKPOS["VKPAUFKRS"].ToString();
            string lfd = dwVKPOS["VKPAUFLFD"].ToString();
            string pos = dwVKPOS["VKPAUFPOS"].ToString();
            if (ITXABPLANData == null)
            {
                ITXABPLANData = new ITXABPLANData();

            }
            ITXABPLANData.DeleteAV95(krs, lfd, pos);
            try
            {
                SetDetail.Clear();
                filter = "EXART LIKE '" + krs + "-" + Helpers.Helper.Right(lfd, 4) + "-" + Helpers.Helper.Right(pos, 3) + "%'";
                DataRow[] rows = SetMaster.Tables["ICC_ABAX"].Select(filter);

                foreach (DataRow row in rows)
                {
                    row.Delete();
                }
                SetMaster.AcceptChanges();
                rows = SetEnv.Tables["ICC_ABAX"].Select(filter);

                foreach (DataRow row in rows)
                {
                    row.Delete();
                }
                SetEnv.AcceptChanges();
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void btnPrintAV95_Click(object sender, RoutedEventArgs e)
        {
            ITXEXRPT.dsSource = SetDetail;
            //ITXEXRPT.dsSource.Merge(SetEnv);
            ITXEXRPT.DocType = "JLTONAV95";
            //ITXEXRPT.DocType = "JLTAV95PLAN";
            ITXEXRPT.strExcelFile = @"\JLT\JLTONAV95.xls";
            string filename = ITXEXRPT.WriteExcelReport();
        }

        private void WeftTech_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwWEFT == null)
                    return;
                string ABAID = dwWEFT["ABAID"].ToString();
                var qMU = from DataRow dwRow in SetDetail.Tables["ICC_ABAX"].AsEnumerable()
                          where dwRow["ABAID"].ToString() == ABAID
                          select dwRow;
                foreach (DataRow row in qMU)
                {
                    row.ItemArray = dwWEFT.ItemArray;
                }
                INTEXDBC.UpdateICC_ABAX(dwWEFT, 1);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void WarpingTech_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (dwWARP == null)
                    return;
                string ABAID = dwWARP["ABAID"].ToString();
                var qMU = from DataRow dwRow in SetEnv.Tables["ICC_ABAX"].AsEnumerable()
                          where dwRow["ABAID"].ToString() == ABAID
                          select dwRow;
                foreach (DataRow row in qMU)
                {
                    row.ItemArray = dwWARP.ItemArray;
                }
                INTEXDBC.UpdateICC_ABAX(dwWARP, 1);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void BeaNum_LostFocus(object sender, RoutedEventArgs e)
        {
            if (dwWARP == null)
                return;
            try
            {
                double UENDS = Convert.ToDouble(dwWARP["UENDS"].ToString());
                double TTENDS = Convert.ToDouble(dwWARP["TTENDS"].ToString());
                //double UNITNUM = Convert.ToDouble(dwWARP["UNITNUM"].ToString());
                TextBox tb = sender as TextBox;
                double UNITNUM = Convert.ToDouble(tb.Text);
                if (UNITNUM == 0)
                    return;
                UENDS = Math.Floor(TTENDS / UNITNUM);
                dwWARP["UENDS"] = UENDS;
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }

        private void TXTNGR02_KeyDown(object sender, KeyEventArgs e)
        {
            if (dwRawYarn == null)
            {
                MessageBox.Show("请选择纱线");
                return;
            }
            try
            {
                TextBox tb = sender as TextBox;
                if (e.Key != System.Windows.Input.Key.Enter)
                    return;
                vm.NGR02 = Convert.ToDouble(tb.Text); 
                double BASEQTY = Convert.ToDouble(dwRawYarn["ABASSTKWG"].ToString()) / 1000;
                //vm.MQTY = Math.Ceiling((vm.NGF02 / vm.GF01 * BASEQTY * (1 - vm.GR02 / 100)) / (1 - vm.NGR02 / 100));
                double RQTY = BASEQTY * (1 - vm.GR02*0.01) * vm.GF01 / (vm.GF02);
                vm.MQTY = Math.Ceiling(RQTY * vm.NGF02 / vm.GF01 / (1 - vm.NGR02 * 0.01));
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }

        private void TXTNGF02_KeyDown(object sender, KeyEventArgs e)
        {
            if (dwRawYarn == null)
            {
                MessageBox.Show("请选择纱线");
                return;
            }
            try
            {
                TextBox tb = sender as TextBox;
                if (e.Key != System.Windows.Input.Key.Enter)
                    return;
                vm.NGF02 = Convert.ToDouble(tb.Text);
                double BASEQTY = Convert.ToDouble(dwRawYarn["ABARESMG"].ToString()) / 1000;
                double RQTY = BASEQTY * (1 - vm.GR02 * 0.01) * vm.GF01 / (vm.GF02 );
                vm.MQTY = Math.Ceiling(RQTY * vm.NGF02 / vm.GF01 / (1 - vm.NGR02 * 0.01));
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }

        }

        private void TextBox_KeyDown(object sender, KeyEventArgs e)
        {
            TextBox tb = sender as TextBox;
            tb.Text = tb.Text.Trim();
        }

        private void BeamEnds_LostFocus(object sender, RoutedEventArgs e)
        {
            if (dwWARP == null)
                return;
            double UNITNUM = Convert.ToDouble(dwWARP["UNITNUM"].ToString());
            double TTENDS = Convert.ToDouble(dwWARP["TTENDS"].ToString());
            //double UNITNUM = Convert.ToDouble(dwWARP["UNITNUM"].ToString());
            TextBox tb = sender as TextBox;
            double UENDS = Convert.ToDouble(tb.Text);
            if (UENDS == 0)
                return;
            UNITNUM = Math.Round(TTENDS / UENDS);
            dwWARP["UNITNUM"] = UNITNUM;
        }

        private void btnAddRatio_Click(object sender, RoutedEventArgs e)
        {

        }

        

    }
}
